package com.example.memo.db;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.memo.entity.UserInfo;

public class UserHelper extends SQLiteOpenHelper {
    private static final String DB_NAME = "UserSQLite.db";
    private static final String TABLE_NAME = "User";
    private static final String CREATE_TABLE = "create table " + TABLE_NAME +
            "(userid integer primary key autoincrement,account text,password text);";

    public UserHelper(Context context){
        super(context,DB_NAME,null,1);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    }

//    注册
    public long register(String account,String password){
        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("account",account);
        values.put("password",password);
        return db.insert(TABLE_NAME,null,values);
    }

//    登陆
    @SuppressLint("Range")
    public UserInfo login(String account){
        SQLiteDatabase db = getReadableDatabase();
        UserInfo userInfo = null;
        Cursor cursor = db.query(TABLE_NAME,null,"account = ?",
                new String[]{account},null,null,null);
        if(cursor.moveToNext()){
            int userid = cursor.getInt(cursor.getColumnIndex("userid"));
            String password = cursor.getString(cursor.getColumnIndex("password"));
            userInfo = new UserInfo(userid,account,password);
        }
        cursor.close();
        return userInfo;
    }

//    修改密码
    public void changePassWord(String account,String password){
        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("password",password);
        db.update(TABLE_NAME,values,"account like ?",new String[]{account});
    }
}
